﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace LiveNation.Utilities {
	public static class NameValueCollectionExtensions {
		/// <summary>
		/// Returns NameValueCollection with selected keys removed
		/// </summary>
		/// <param name="keys">Keys to remove</param>
		/// <param name="removeEmptyVars">If true, variables with empty values are also removed (to tidy up)</param>
		public static NameValueCollection RemoveKeys(this NameValueCollection nvc, IEnumerable<string> keysToRemove, bool removeEmptyValues) {
			var newNvc = new NameValueCollection();

			// Transform to lower case for case-insensitive comparision
			keysToRemove = keysToRemove.Select(k => k.ToLowerInvariant());
			
			foreach (var key in nvc.AllKeys) {
				var lowerKey = key.ToLowerInvariant();
				if (!keysToRemove.Contains(lowerKey)
					&& (!removeEmptyValues || !string.IsNullOrEmpty(nvc[key])))
					newNvc.Add(key, nvc[key]);
			}

			return newNvc;
		}

		/// <summary>
		/// Returns string like query string ({0}={1}&....)
		/// </summary>
		/// <remarks>Surely this function is built somewhere???</remarks>
		public static string ToHttpValueString(this NameValueCollection nvc) {
			var sb = new StringBuilder();
			foreach (var key in nvc.AllKeys) {
				if (sb.Length > 0)
					sb.Append("&");
				sb.AppendFormat("{0}={1}", key, nvc[key]);
			}
			return sb.ToString();
		}
	}
}
